<template>
    <treeselect
    v-model="val"
    :options="options" />
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'TreeSelectForForm',
  components: {
    Treeselect
  },
  props: {
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    labelKey: {
      type: String,
      default: () => {
        return 'label'
      }
    },
    idKey: {
      type: String,
      default: () => {
        return 'id'
      }
    },
    value: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      options: [],
      val: null
    }
  },
  watch: {
    data: {
      handler: function (val, oldVal) {
        this.options = this.renderOption(val)
        console.log(this.options)
      },
      immediate: true,
      deep: true
    },
    val (value) {
      this.$emit('input', value)
    },
    value (val) {
      this.val = val
    }
  },
  methods: {
    renderOption (val) {
      // 渲染option
      let formatData = []
      if (val instanceof Array && val.length > 0) {
        val.map(item => {
          const cell = {
            id: item[this.idKey],
            label: item[this.labelKey], // 显示
            isDefaultExpanded: true
          }
          if (typeof item.checked !== 'undefined') cell.checked = item.checked
          if (typeof item.selected !== 'undefined') cell.selected = item.selected
          if (item.children) {
            cell.children = this.renderOption(item.children)
          }
          formatData.push(cell)
        })
        return formatData
      }
    }
  }
}
</script>
